import gpio
import i2c
import os


class BH1750:
    def __init__(self, i2c_id, sda_pin, scl_pin, freq):
        self.i2c_id = i2c_id
        self.sda_pin = sda_pin
        self.scl_pin = scl_pin
        self.freq = freq

        self.i2c_addr = 0x23 << 1
        self.init_gpio()

    def init_gpio(self):
        gpio.gpio_init(self.sda_pin)
        func = gpio.query_func_value(self.sda_pin, 'I2C1_SDA')
        gpio.set_func(self.sda_pin, func)
        gpio.gpio_init(self.scl_pin)
        func = gpio.query_func_value(self.scl_pin, 'I2C1_SCL')
        gpio.set_func(self.scl_pin, func)

    def open(self):
        r = 0
        r += i2c.i2c_init(self.i2c_id, self.freq)
        r += i2c.write(self.i2c_id, self.i2c_addr, [0x01])
        r += i2c.write(self.i2c_id, self.i2c_addr, [0x10])
        return r

    def read(self):
        r, d = i2c.read(self.i2c_id, self.i2c_addr, 2)
        if r == 0:
            d = (((d[0] << 8) + d[1]) / 1.2)
        return d


i2c_id = 1
sda_pin = 0
scl_pin = 1
freq = 400000

bh1750 = BH1750(i2c_id, sda_pin, scl_pin, freq)

